在 C 中實際上是使用Stream I/O的方式來存取資料
也就是說,當打開一個檔案後
OS那邊會將一部分的資料先讀起來在一個暫存的Buffer裡
然後FILE這個pointer就會去指向這個buffer
每讀取一個字元時
它就會往前移動一個
同樣的
當我們在寫入的時候
當我們完成像是fprintf時
它也是先寫入這個buffer中
直到這個buffer被flush或是寫出到device中
才會真正的做改變。
| 值 | 功能 | 
|---|---|
| r | 假如檔案不存在則失敗 | 
| w | 若檔案存在,則內容會被覆蓋 | 
| a | 不重置目前的內容,可以繼續添加內容 | 
| r+ | 檔案必需存在 | 
| w+ | 檔案存在就修改,不存在就開新檔案 | 
| a+ | 檔案不存在就開新檔案,存在就不重置內容繼續添加內容 | 
開啟檔案之前要先定義一個指標來指向檔案的變數
每次使用結束都必須關閉檔案
EOF 是保留自,代表 End of File
在EOF的時候return 0;否則會 return non-zero
開啟檔案依序顯示文字
text.txt
hello
1
2
3
example01.c
#include <stdio.h>
int main(void)
{
  FILE *myfile;
  myfile = fopen("test.txt", "r");
  char word;
  if (myfile == NULL)
  {
    printf("file not found!");
    return 1;
  }
  else
  {
    while ((word = fgetc(myfile)) != EOF)
    {
      printf("%c", word);
    }
    fclose(myfile);
    return 0;
  }
}
/**
hello
1
2
3
**/
while會依序找到每一個字
直到檔案結束(EOF)
但是這樣一個字一個字跑實在有點麻煩
#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp;
  char *line = NULL;
  size_t len = 0;
  ssize_t read;
  fp = fopen("test.txt", "r");
  if (fp == NULL)
  {
    printf("File Not Found");
    return 0;
  }
  else
  {
    while ((read = getline(&line, &len, fp) != -1))
    {
      printf("Retrieved line of length %zu \n", read);
      printf("%s", line);
    }
    fclose(fp);
    if (line)
    {
      free(line);
    }
    return 0;
  }
}
/**
output:
Retrieved line of length 1
hello
Retrieved line of length 1
1
Retrieved line of length 1
2
Retrieved line of length 1
3%
**/
我們再修改一下上面的程式碼
#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp, *newFile;
  char *line = NULL;
  size_t len = 0;
  ssize_t read;
  fp = fopen("test.txt", "r");
  newFile = fopen("newFile.txt", "w+");
  if (fp == NULL)
  {
    printf("File Not Found");
    return 0;
  }
  else
  {
    while ((read = getline(&line, &len, fp) != -1))
    {
      fputs(line, newFile);
    }
    fclose(fp);
    if (line)
    {
      free(line);
    }
    return 0;
  }
}
只是將printf 修改為 fputs
就可以將檔案內容完整複製到另外一個新的檔案
很簡單吧!